from pydantic import BaseModel, Field, field_validator, ConfigDict
from typing import Optional
from decimal import Decimal
from datetime import date


class BaseAccount(BaseModel):
    """账单记录基础模型"""
    amount: float = Field(..., description="金额", ge=0.01, le=999999.99, example=30.00)
    type: str = Field(..., description="收支类型", example="expense")
    category: str = Field(..., description="分类", example="餐饮")
    remark: str = Field(..., description="备注", example="午餐")
    record_date: Optional[date] = Field(None, description="记录日期")
    
    # @field_validator('type')
    # @classmethod
    # def validate_type(cls, v):
    #     if v not in ['income', 'expense']:
    #         raise ValueError('类型必须是 income 或 expense')
    #     return v
    
    # @field_validator('category')
    # @classmethod 
    # def validate_category(cls, v, info):
    #     # print(f"正在验证分类: {v} {info} {info.data}")
    #     if info.data and 'type' in info.data:
    #         if info.data['type'] == 'expense' and v not in ['餐饮', '交通', '购物', '娱乐', '居家', '医疗', '教育', '其他']:
    #             raise ValueError('无效的支出分类')
    #         elif info.data['type'] == 'income' and v not in ['工资', '奖金', '投资', '兼职', '其他']:
    #             raise ValueError('无效的收入分类')
    #     return v


class AccountCreate(BaseAccount):
    """创建账单记录模型"""
    family_id: Optional[int] = Field(None, description="家庭ID，可选择记录到特定家庭账本中")
    user_id: Optional[int] = Field(None, description="用户ID")  

    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "amount": 30.50,
                "type": "expense",
                "category": "餐饮",
                "remark": "午餐",
                "record_date": "2024-09-02",
                "family_id": 1,
                "user_id":1
            }
        }
    )


class AccountUpdate(BaseModel):
    """更新账单记录模型"""
    amount: Optional[float] = Field(None, description="金额", ge=0.01, le=999999.99)
    type: Optional[str] = Field(None, description="收支类型")
    category: Optional[str] = Field(None, description="分类")
    remark: Optional[str] = Field(None, description="备注")
    record_date: Optional[date] = Field(None, description="记录日期")
    
    @field_validator('type')
    @classmethod
    def validate_type(cls, v):
        if v is not None and v not in ['income', 'expense']:
            raise ValueError('类型必须是 income 或 expense')
        return v


class AccountListResponse(BaseModel):
    """账单记录列表响应模型"""
    id: int
    amount: str
    type: str
    category: str
    remark: str
    record_date: str
    created_at: str
    
    model_config = ConfigDict(from_attributes=True)


class AccountStatisticsResponse(BaseModel):
    """账单统计响应模型"""
    income: str
    expense: str
    balance: str
    income_formatted: str
    expense_formatted: str
    balance_formatted: str
